<template>
  <div>
    <a-modal v-model:open="open" title="新增字典" @ok="handleOk">
      <EditForm :hidePassword="false" ref="rForm"></EditForm>
    </a-modal>
  </div>
</template>
<script lang="ts" setup>
import { ref, defineEmits, nextTick } from 'vue'
import EditForm from './edit-form.vue'
import { type CreateUserDto, updateUserApi } from '@/api/user.api.ts'
import { localhostUpload } from '@/api/upload.api.ts'
import { userRegisterApi } from '@/api/auth.api.ts'

const emits = defineEmits(['editOk'])

const open = ref<boolean>(false)
const Record = ref()

const showModal = (record: CreateUserDto) => {
  open.value = true
  Record.value = { ...record }
  nextTick(() => {
    rForm.value?.setFormState(Record.value)
  })
}

const rForm = ref()
const handleOk = () => {
  rForm.value.submit().then(async (res: CreateUserDto) => {
    if (res.avatarFile) {
      const formData = new FormData()
      formData.append('file', res.avatarFile)
      const { fileUrl } = await localhostUpload(formData)
      res.avatar = fileUrl
    }
    delete res.avatarFile
    updateUserApi(Record.value.id, {
      account: res.account,
      username: res.username,
      roleId: res.roleId,
      avatar: res.avatar,
    }).then(() => {
      open.value = false
      emits('editOk')
    })
  })
}

defineOptions({
  name: 'EditDictModal',
})
defineExpose({
  showModal,
})
</script>
